package com.yangzb.word;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumPr;

import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class Word {
    public static void write(String title,List<String> content) throws IOException {
        try (XWPFDocument document = new XWPFDocument()) {
            OutputStream stream = null;
            BufferedOutputStream bufferStream = null;
            stream = new FileOutputStream(new File("/Users/yzb/Downloads/1.docx"));
            bufferStream = new BufferedOutputStream(stream, 1024);
            // 创建一个段落
            XWPFParagraph p1 = document.createParagraph();
            // 设置居中
            p1.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun r1 = p1.createRun();
            // 是否加粗
            r1.setBold(true);
            // 与下一行的距离
            r1.setTextPosition(30);
            r1.setText(title);
            XWPFParagraph p2 = document.createParagraph();
            XWPFRun r2 = p2.createRun();
            for (int i = 0; i < content.size(); i++) {
                r2.setText(i + 1 + "、" + content.get(i));
                r2.addCarriageReturn();
            }
            // 设置字体
            r2.setFontFamily("仿宋");
            r2.setFontSize(14);// 字体大小
            document.write(stream);
            stream.close();
            bufferStream.close();
        }

    }

    public static void main(String[] args) throws IOException {
        write("测试",read());
    }

    public static List<String> read(){
        List<String> contents= new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream(new File("/Users/yzb/Downloads/20221010#陕西客经强制关停#详细设计.docx"));
            XWPFDocument document = new XWPFDocument(fis);

            // 读取段落
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph para : paragraphs) {
                if (para.getCTP() != null&&para.getCTP().getPPr() != null&&para.getCTP().getPPr().getNumPr() != null) {
                    CTNumPr numPr = para.getCTP().getPPr().getNumPr();
                    BigInteger val = numPr.getNumId().getVal();
                    System.out.println(val+":"+para.getText());
                }
                System.out.println(para.getText());
                contents.add(para.getText());
            }

            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contents;
    }
}
